package me.liuyu2783.dubbo.sample.netty;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.net.URI;

/**
 * me.liuyu2783.dubbo.sample.netty
 *
 * @author liuyu2783
 * @date 2020-3-3
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        //解析url
        URI uri = new URI(fullHttpRequest.uri());
        //http://120.0.0.1:8081/me.liuyu2783.peyService/getPetName
        String serverName = uri.getPath().split("/")[0];
        String methodName = uri.getPath().split("/")[1];
        //查账方法
        try {
            Object result = findMethod(serverName,methodName).apply(fullHttpRequest.content());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        //业务处理
        FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html;charset=utf-8");
        httpResponse.content().writeBytes("您好".getBytes());
        channelHandlerContext.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
    }
}
